/*
 * @Descripttion: 
 * @version: 
 * @Author: 
 * @Date: 2022-04-25 11:40:02
 * @LastEditors: weidelong
 * @LastEditTime: 2022-05-07 16:36:31
 */
const express = require('express')
const user = require('../db/userSchema_mobile')
const router = express.Router()

router.post('/editUserInfo', (req, res) => {
	const {id} = req.body
	user.findOne({id}).exec(function(err,data){
		// 先查询到指定的数据data
		// 然后修改数据
		if (data) {
			for(const [key, value] of Object.entries(req.body)) {
				if (key !== 'id') {
					data[key] = value
				}
			}
			data.save(function(err){
				// err在修改错误时报错有值
				if (err) {
					res.send({
						status: 500,
						msg: '修改失败'
					})
				} else {
					const info = {
						id: data.id,
						phone: data.phone,
						img: data.userImg,
						name: data.userName,
						sex: data.sex
					}
					res.send({
						status: 200,
						data: {
							code: 0,
							userObj: info
						},
						msg: '修改成功'
					})
				}
			})
		}	
	})
})

// 获取用户信息
router.get('/getUserInfo', async (req, res) => {
	const { id } = req.query
	const userobj = await user.findOne({id})
	if (userobj) {
		const obj = {
			id: userobj.id,
			name: userobj.userName,
			phone: userobj.phone,
			img: userobj.userImg,
			sex: userobj.sex
		}
		res.send({
			status: 200,
			data: {
				code: 0,
				userobj: obj
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询失败'
		})
	}
})

/* 导出router对象 */
module.exports = router